﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebEntities;
using com.subb.WebInfo;

namespace WebUI.ActionFilters
{
    public class NewsViewCountAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            List<int> accessNewsList = filterContext.HttpContext.Session["AccessNewsList"] as List<int>;
            if (accessNewsList == null)
            {
                accessNewsList = new List<int>();
            }

            int newsId;
            string id = (filterContext.RequestContext.RouteData.Values["id"] == null) ? "0" : filterContext.RequestContext.RouteData.Values["id"].ToString();
            if (!int.TryParse(id, out newsId))
            {
                newsId = 0;
            }

            if (newsId != 0)
            {
                //检查当前会话是否访问过这条记录
                int count = accessNewsList.Where(c => c.Equals(newsId)).Count();
                if (count <= 0)
                {
                    string[] spiders = new string[] { "baiduspider, googlebot", "spider" };
                    string userAgent = filterContext.HttpContext.Request.UserAgent;
                    if (!string.IsNullOrWhiteSpace(userAgent))
                    {
                        foreach (var spider in spiders)
                        {
                            if (userAgent.ToLower().Contains(spider))
                            {
                                return;
                            }
                        }
                        WI_NewsDAL ndal = new WI_NewsDAL();
                        if (ndal.UpdateViewCount(newsId))
                        {
                            accessNewsList.Add(newsId);
                            filterContext.HttpContext.Session["AccessNewsList"] = accessNewsList;
                        }
                    }
                }
            }
        }
    }
}